#!/bin/sh

# Part of Zombie Navigator
# Copyright © 2016  Zombie Navigator Developers

addonExt=".xpi"


# TODO: Colors not good
TERM_OKBLUE='\033[94m'
#TERM_OKGREEN='\033[92m'
TERM_OKGREEN='\033[32m'
#TERM_WARNING='\033[93m'
TERM_WARNING='\033[33m'
TERM_FAIL='\033[91m'
TERM_UNIMPORTANT='\033[95m'
TERM_TEST='\033[96m'
#TERM_TEST='\033[37m'

TERM_BOLD='\033[1m'
TERM_UNDERLINE='\033[4m'

TERM_ENDC='\033[0m'


mylog () {
	[ -t 2 ] && [ -z "$ZOMBIE_NOCOLOR" ] && {
		printf "${TERM_UNIMPORTANT}[%s]${TERM_ENDC} ${TERM_OKBLUE}%s${TERM_ENDC}\n"	"`date`" "$@" >&2
	:;} || {
		echo "[`date`] $@" >&2
	}
}

mynotice () {
	[ -t 2 ] && [ -z "$ZOMBIE_NOCOLOR" ] && {
		printf "${TERM_UNIMPORTANT}[%s]${TERM_ENDC} ${TERM_OKGREEN}%s${TERM_ENDC}\n"	"`date`" "$@" >&2
	:;} || {
		echo "[`date`] $@" >&2
	}
}

mywarn () {
	[ -t 2 ] && [ -z "$ZOMBIE_NOCOLOR" ] && {
		printf "${TERM_BOLD}[%s]${TERM_ENDC} ${TERM_UNDERLINE}Warning${TERM_ENDC}: ${TERM_WARNING}%s${TERM_ENDC}\n"	"`date`" "$@" >&2
	:;} || {
		echo "[`date`] Warning: $@" >&2
	}
}

unset LANGUAGE
LANG=C
LC_ALL=C

dir="`dirname "$0"`"
dir="`cd "$dir"; cd .. ; pwd`"
cd "$dir/src"

. ../version_info


# Create .xpi
while [ "$#" -gt 0 ] ; do
	case "$1" in
		--minify-js)
			minify_js=1
			;;
		--help)
			echo "Usage: $0 [--minify-js]"
			exit
			;;
		--version)
			echo "Will build: '$addon_version'"
			exit
			;;
	esac
	shift
done


mylog "$addon_id version $addon_version build script"

buildsDir="$dir/builds"
buildTmpDir="$dir/.build"

mkdir -p "$buildsDir"
rm -rf "$buildTmpDir"

cd ..
cp -rf src "$buildTmpDir"
cd "$buildTmpDir"

mylog "Excluding development files..."

rm -fv ./debug.js
rm -frv ./data/debug/

mylog "Optimizing files..."

find . -type f \( -name '*.html' -or -name '*.js' \) -execdir sh -c 'egrep -v "^\s*$|vim:" "$1" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;

find . -type f -name '*.css' -execdir sh -c 'egrep -v "^\s*$|vim:" "$1" | tr -d "\t\n" | perl -pe "s/\s*([{:>+,])\s*/\1/g ; s/;}/}/g" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;

find . -type f -name '*.json' -execdir sh -c 'egrep -v "^\s*$" "$1" | sed "s/^ *//" | tr -d "\n" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;

#find . -type f -name '*.js' -exec sh -c 'egrep -v "^\s*@([^l]([^i]([^c]([^e]([^n]([^s]([^e].*)?)?)?)?)?)?)?($|[^a-z]+)" "$1" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;

jsmin_sed_path="$dir/tools/optimization/js-min.sed"
jsmin_egrep='^\s*(/\*\*?)?\s*@(file|module|public|method|private|protected)($|[^a-z])|^\s*/\*\*\s*[Ee]xports\s\*/\s*$|^\s*/\*!_DEBUGONLY_!\*/'

find . -type f -name '*.js' -exec sh -c 'egrep -v "$3" "$1" | sed -f "$2" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} "$jsmin_sed_path" "$jsmin_egrep" \;

#grep -v '^\s*$' < './install.rdf' > './install.rdf~'
#sed 's/^\s*//' < './install.rdf~' > './install.rdf'
#rm -fv './install.rdf~'

[ "$minify_js" ] && {
	mynotice "EXPERIMENTAL: Doing JS minification..."
	mynotice "This may result in problems!"
	find . -type f -name '*.js' -exec sh -c 'echo "Compressing: $1" ; ../bin/estidy < "$1" > "$1.tmp" && mv -f "$1.tmp" "$1" || rm -f "$1.tmp"' -- {} \;
} || {
	mylog "Skipping JS minification!"
}

cat ./build.meta >> ./index.js

du -a -h --apparent-size --max-depth 1 || du -ahd1


mylog "Building the addon..."
mynotice "Please ignore JPM warnings about the 'semver' (if any) (NOT relevant for stable release versions)"
mylog "Because we use '~' for prereleases (for consistence with GNU/Linux conventions)"

../bin/build | egrep -v 'semver|^\s*$|semantic|versioning rules|values indicating major,|^"1\.4\.56"|^"0\.0\.1"$|^"1\.0\.0rc4"$' || {
	mylog "[ERROR] JPM: Failed"
	exit 1
}


if which unzip >/dev/null 2>&1 ; then
	mkdir .built
	cd .built
	unzip ../*"${addonExt}" | tr '\n' '\r'
	s10='          '
	printf "$s10$s10$s10$s10$s10$s10$s10$s10\r"
	grep -v '^\s*$' < './install.rdf' > './install.rdf~'
	sed 's/^\s*//' < './install.rdf~' > './install.rdf'
	rm -fv './install.rdf~'
	
	# This is safe
	buildName=`printf '%s' ../*"${addonExt}"`
	rm "$buildName"
	
	# Skipping directory entries
	# Assuming no space characters in file names
	zip ../.rebuild.zip `find . -type f` | tr '\n' '\r'
	printf "$s10$s10$s10$s10$s10$s10$s10$s10\r"
	mv -f ../.rebuild.zip "$buildName"
	cd ..
else
	mywarn "NOTE: Skipping post-build optimization (unzip needed)..."
fi

if which advzip >/dev/null 2>&1 ; then
	# AdvanceCOMP available
	mylog "Recompressing..."
	advzip -k -z -4 -i 200 ./*"${addonExt}"
else
	mywarn "NOTE: Skipping recompression (AdvanceCOMP needed)..."
fi

if which strip-nondeterminism >/dev/null 2>&1 ; then
	# strip-nondeterminism available
	mylog "Trying to strip nondeterminism (not yet tested)..."
	strip-nondeterminism -t zip ./*"${addonExt}"
else
	mywarn "NOTE: Deterministic build disabled (strip-nondeterminism needed)..."
fi

sha256sum ./*"${addonExt}"

mylog "Saving the archive..."
targetDir="$buildsDir/`date +%s`"
[ "$minify_js" ] && targetDir="$targetDir.min-js"
mkdir -p "$targetDir"
mv -b -v ./*"${addonExt}" "$targetDir"/ || mv -n -v ./*"${addonExt}" "$targetDir"/
chmod a-wx "$targetDir"/*
(
	cd "$buildsDir"
	rm -f latest
	ln -sv "./`basename "$targetDir"`" latest
)

cd ..
rm -rf "$buildTmpDir"

mynotice "Done? ($addon_id $addon_version)"


# vim: ts=4 noet ai

